import React, { useEffect } from 'react';
import { BrowserRouter } from 'react-router-dom';
import { Provider, useDispatch } from 'react-redux';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import Router from './router';
import { store } from './store';
import { setToken } from './store/slices/auth';
import { setMenus } from './store/slices/menu';
import './App.less';

// 初始化组件，用于加载本地存储的状态
const AppInitializer: React.FC = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    // 从本地存储加载token和菜单数据
    const token = localStorage.getItem('token');
    const menuData = localStorage.getItem('menuData');

    if (token) {
      dispatch(setToken(token));
    }

    if (menuData) {
      try {
        const menus = JSON.parse(menuData);
        dispatch(setMenus(menus));
      } catch (error) {
        console.error('Failed to parse menu data', error);
      }
    }
  }, [dispatch]);

  return <Router />;
};

const App: React.FC = () => {
  return (
    <Provider store={store}>
      <ConfigProvider locale={zhCN}>
        <BrowserRouter>
          <AppInitializer />
        </BrowserRouter>
      </ConfigProvider>
    </Provider>
  );
};

export default App;